/**
 * This file is part of Idegen, the application to create IDE project files.
 *
 * @copyright Copyright (c) 2011-2012, Walter Tamboer http://waltertamboer.nl
 * @file Idegen/Idegen/IdegenGenerator.cpp
 */

#include "Idegen/PrecompiledHeader.hpp"
#include "Idegen/Application/Settings.hpp"
#include "Idegen/Idegen/IdegenGeneratorType.hpp"
#include "Idegen/Idegen/IdegenGenerator.hpp"

namespace Idegen
{
	IdegenGenerator::IdegenGenerator()
	{
	}

	IdegenGenerator::~IdegenGenerator()
	{
	}

	std::string IdegenGenerator::GetName() const
	{
		return m_Name;
	}

	std::string IdegenGenerator::GetOutputPath() const
	{
		return m_OutputPath;
	}
	
	IdegenProjectList IdegenGenerator::GetProjects() const
	{
		return m_Projects;
	}

	IdegenGeneratorType IdegenGenerator::GetType() const
	{
		return m_Type;
	}

	void IdegenGenerator::ParseAttributes( Settings* settings, TiXmlElement* parent )
	{
		TiXmlAttribute* attrib = parent->FirstAttribute();
		while ( attrib != NULL )
		{
			const std::string attribName = attrib->Name();
			const std::string attribValue = settings->ParseVariables( attrib->Value() );
			
			if ( attribName == "type" )
			{
				m_Type = StringToGeneratorType( attribValue );
			}
			else if ( attribName == "name" )
			{
				m_Name = attribValue;
			}
			else if ( attribName == "copy" )
			{
				std::string copiedName = attribValue;
			}
			else if ( attribName == "output" )
			{
				m_OutputPath = attribValue;
			}

			attrib = attrib->Next();
		}
	}

	void IdegenGenerator::ParseProject( Settings* settings, TiXmlElement* parent )
	{
		std::string projectName;
		if ( ParseAttributeString( parent, "name", projectName ) )
		{
			// Parse any variables in the project name:
			projectName = settings->ParseVariables( projectName );

			// Now try to find the project:
			IdegenProject* project = settings->FindProject( projectName );
			if ( project == NULL )
			{
				// Try to create the project by its name:
				project = settings->ParseProject( projectName );
				if ( project == NULL )
				{
					// The project has not been found; maybe it is an inline definition:
					TiXmlElement* childElement = parent->FirstChildElement();
					if ( childElement != NULL )
					{
						project = settings->ParseProject( parent );
					}
				}
			}

			if ( project != NULL )
			{
				m_Projects.push_back( project );
			}
		}
	}

	void IdegenGenerator::ParseProjects( Settings* settings, TiXmlElement* parent )
	{
		TiXmlElement* element = parent->FirstChildElement( "i:project" );
		while ( element != NULL )
		{
			ParseProject( settings, element );

			element = element->NextSiblingElement( "i:project" );
		}
	}

	void IdegenGenerator::Unserialize( Settings* settings, TiXmlElement* parent )
	{
		settings->ParseIncludes( parent );
		ParseAttributes( settings, parent );
		ParseProjects( settings, parent );
	}
}
